/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelaSimulador.java
 *
 * Created on 25/05/2012, 11:52:11
 */
package aplicacao;

import auxiliar.LinhaTP;
import auxiliar.Pagina;
import auxiliar.Processo;
import auxiliar.Quadro;
import hardware.MemoriaPrincipal;
import hardware.MemoriaSecundaria;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author lcc
 */
public class TelaSimulador extends javax.swing.JFrame {

    static BufferedReader in;
    public static DefaultTableModel tabelaMP;
    public static DefaultTableModel tabelaMS;
    public static javax.swing.JTabbedPane painelTP;
    public static javax.swing.JLabel labelTP;
    public static final String CELULA_VAZIA = "-----";
    private static final char OPERACAO_NEW = 'N';
    private static final char OPERACAO_READ = 'R';
    private static final char OPERACAO_WRITE = 'W';
    private static List<Processo> processos = new ArrayList<Processo>();
    private static List<Integer> processosInvalidos = new ArrayList<Integer>();
    private static List<JTable> tabelasDePagina = new ArrayList<JTable>();
    public static int numFaltaDePaginas = 0;
    public static int relogio = 0;
    public static final int COLUNA_NUM_QUADRO = 0;
    public static final int COLUNA_NUM_PROCESSO = 1;
    public static final int COLUNA_NUM_PAGINA = 2;
    public static final int COLUNA_ULTIMA_REFERENCIA = 3;
    public static final int COLUNA_VERSAO_MP = 4;
    public static final int COLUNA_ENTRADA = 5;
    public static final int COLUNA_VERSAO_MS = 3;
    public static final int COLUNA_NUM_PAGINA_TP = 0;
    public static final int COLUNA_NUM_QUADRO_TP = 1;
    public static final int COLUNA_P = 2;
    public static final int COLUNA_M = 3;

    public static List<Processo> getProcessos() {
        return processos;
    }

    public static void setProcessos(List<Processo> processos) {
        TelaSimulador.processos = processos;
    }

    public static List<JTable> getTabelasDePagina() {
        return tabelasDePagina;
    }

    public static void setTabelasDePagina(List<JTable> tabelasDePagina) {
        TelaSimulador.tabelasDePagina = tabelasDePagina;
    }

    public JTabbedPane getTabelasDePaginaPane() {
        return tabelasDePaginaPane;
    }

    public void setTabelasDePaginaPane(JTabbedPane tabelasDePaginaPane) {
        this.tabelasDePaginaPane = tabelasDePaginaPane;
    }

    public static void adicionarTP(Processo processo) {

        JTable jtable = new JTable();

        inicializaJTable(jtable);

        javax.swing.JScrollPane jScrollPane = new javax.swing.JScrollPane();
        jScrollPane.setViewportView(jtable);

        if (!painelTP.isVisible()) {
            painelTP.setVisible(true);
            labelTP.setVisible(true);
        }

        painelTP.addTab("P" + processo.getId(), jScrollPane);

        DefaultTableModel tpInterface = (DefaultTableModel) jtable.getModel();
        processo.getTabelaDePaginas().setTabInterface(tpInterface);
        for (int i = 0; i < processo.getPaginas().size(); i++) {
            Object[] linha = new Object[4];
            linha[0] = "Página " + i;
            linha[1] = TelaSimulador.CELULA_VAZIA;
            linha[2] = 0;
            linha[3] = 0;
            tpInterface.addRow(linha);
        }
    }

    public static void incrementaFaltaDePaginas() {
        numFaltaDePaginas++;
    }

    public static void atualizaTabelaMP(Pagina pagina, Quadro quadro) {
        int numQuadro = quadro.getEnderecoFisico();
        Processo processo = pagina.getProcesso();
        int i = processo.getPaginas().indexOf(pagina);
        TelaSimulador.tabelaMP.setValueAt("Página " + i, numQuadro, TelaSimulador.COLUNA_NUM_PAGINA);
        TelaSimulador.tabelaMP.setValueAt("Processo " + processo.getId(), numQuadro, TelaSimulador.COLUNA_NUM_PROCESSO);
        TelaSimulador.tabelaMP.setValueAt(pagina.getUltimaReferencia(), numQuadro, TelaSimulador.COLUNA_ULTIMA_REFERENCIA);
        TelaSimulador.tabelaMP.setValueAt(pagina.getVersao(), numQuadro, TelaSimulador.COLUNA_VERSAO_MP);
        TelaSimulador.tabelaMP.setValueAt(pagina.getEntradaMP(), numQuadro, TelaSimulador.COLUNA_ENTRADA);
    }

    public static void atualizaTabelaMS(Pagina pagina, Quadro quadro) {
        int numQuadro = quadro.getEnderecoFisico();
        Processo processo = pagina.getProcesso();
        int i = processo.getPaginas().indexOf(pagina);
        TelaSimulador.tabelaMS.setValueAt("Página " + i, numQuadro, TelaSimulador.COLUNA_NUM_PAGINA);
        TelaSimulador.tabelaMS.setValueAt("Processo " + processo.getId(), numQuadro, TelaSimulador.COLUNA_NUM_PROCESSO);
        TelaSimulador.tabelaMS.setValueAt(pagina.getVersao(), numQuadro, TelaSimulador.COLUNA_VERSAO_MS);
    }

    public static void atualizaTabelaDePaginas(Pagina pagina) {
        Processo processo = pagina.getProcesso();
        DefaultTableModel tab = processo.getTabelaDePaginas().getTabInterface();
        int i = processo.getPaginas().indexOf(pagina);
        LinhaTP linha = processo.getTabelaDePaginas().getLinhas().get(i);

        if (linha.getNumQuadro() == -1) {
            tab.setValueAt(TelaSimulador.CELULA_VAZIA, i, TelaSimulador.COLUNA_NUM_QUADRO_TP);
        } else {
            tab.setValueAt("Quadro " + linha.getNumQuadro(), i, TelaSimulador.COLUNA_NUM_QUADRO_TP);
        }
        if (linha.isP()) {
            tab.setValueAt(1, i, TelaSimulador.COLUNA_P);
        } else {
            tab.setValueAt(0, i, TelaSimulador.COLUNA_P);
        }
        if (linha.isM()) {
            tab.setValueAt(1, i, TelaSimulador.COLUNA_M);
        } else {
            tab.setValueAt(0, i, TelaSimulador.COLUNA_M);
        }
    }

    public static String politicaToS() {
        String politica = "";
        String escopo = "";

        if (TelaPrincipal.escopo == TelaPrincipal.ESCOPO_GLOBAL) {
            escopo = "Global";
        } else {
            if (TelaPrincipal.escopo == TelaPrincipal.ESCOPO_LOCAL) {
                escopo = "Local";
            }
        }

        if (TelaPrincipal.politica == TelaPrincipal.POLITICA_FIFO) {
            politica = "FIFO";
        } else {
            if (TelaPrincipal.politica == TelaPrincipal.POLITICA_LRU) {
                politica = "LRU";
            }
        }

        return politica + " - Escopo " + escopo;
    }

    /**
     * Creates new form TelaSimulador
     */
    public TelaSimulador() {
        initComponents();
        this.textTamPagina.setText(String.valueOf(Pagina.getTAMANHO()));
        this.textTamMemPrinc.setText(String.valueOf(MemoriaPrincipal.getTAMANHO() * Pagina.getTAMANHO() + MemoriaPrincipal.getTAMANHO_TP()));
        this.textTamMemSec.setText(String.valueOf(MemoriaSecundaria.getTAMANHO() * Pagina.getTAMANHO() + MemoriaSecundaria.getTAMANHO_TP()));
        this.textLinha.setText("");
        this.textExplicacaoLinha.setText("");
        this.textNumFaltaPaginas.setText(String.valueOf(numFaltaDePaginas));
        this.textPolitica.setText(politicaToS());
        this.textRelogio.setText(String.valueOf(relogio));

        tabelaMP = (DefaultTableModel) this.tableMP.getModel();
        tabelaMS = (DefaultTableModel) this.tableMS.getModel();

        // Inicialização das tabelas que representam a Memória Principal e a Memória Secundária na interface gráfica
        for (int i = 0; i < MemoriaPrincipal.getTAMANHO(); i++) {
            Object[] linha = new Object[5];
            linha[0] = new Integer(i);
            linha[1] = CELULA_VAZIA;
            linha[2] = CELULA_VAZIA;
            linha[3] = CELULA_VAZIA;
            linha[4] = CELULA_VAZIA;
            tabelaMP.addRow(linha);
        }
        for (int i = 0; i < MemoriaSecundaria.getTAMANHO(); i++) {
            Object[] linha = new Object[4];
            linha[0] = new Integer(i);
            linha[1] = CELULA_VAZIA;
            linha[2] = CELULA_VAZIA;
            linha[3] = CELULA_VAZIA;
            tabelaMS.addRow(linha);
        }
        for (int i = 0; i < MemoriaPrincipal.getTAMANHO(); i++) {
            MemoriaPrincipal.getQuadros()[i] = new Quadro(i);
        }
        for (int i = 0; i < MemoriaSecundaria.getTAMANHO(); i++) {
            MemoriaSecundaria.getQuadros()[i] = new Quadro(i);
        }


        painelTP = tabelasDePaginaPane;
        painelTP.setVisible(false);
        labelTP = jlabelTP;
        labelTP.setVisible(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        btnLerProxLinha = new javax.swing.JButton();
        textLinha = new javax.swing.JLabel();
        textTamPagina = new javax.swing.JLabel();
        textTamMemPrinc = new javax.swing.JLabel();
        textTamMemSec = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableMP = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        textExplicacaoLinha = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        textNumFaltaPaginas = new javax.swing.JLabel();
        jlabelTP = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        textPolitica = new javax.swing.JLabel();
        textRelogio = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableMS = new javax.swing.JTable();
        tabelasDePaginaPane = new javax.swing.JTabbedPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Tamanho das Páginas");

        jLabel3.setText("Tamanho da Memória Principal");

        jLabel4.setText("Tamanho da Memória Secundária");

        btnLerProxLinha.setText("Ler próxima linha");
        btnLerProxLinha.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnLerProxLinhaMouseClicked(evt);
            }
        });
        btnLerProxLinha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLerProxLinhaActionPerformed(evt);
            }
        });

        textLinha.setText("label Linha");

        textTamPagina.setText("tamPag");

        textTamMemPrinc.setText("tamMemPrinc");

        textTamMemSec.setText("tamMemSec");

        jLabel2.setText("Linha atual");

        tableMP.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Quadro", "# do Processo", "# da Página", "U.R.", "V", "E"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableMP.setCellSelectionEnabled(true);
        jScrollPane1.setViewportView(tableMP);
        tableMP.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableMP.getColumnModel().getColumn(0).setResizable(false);
        tableMP.getColumnModel().getColumn(0).setPreferredWidth(60);
        tableMP.getColumnModel().getColumn(1).setResizable(false);
        tableMP.getColumnModel().getColumn(1).setPreferredWidth(110);
        tableMP.getColumnModel().getColumn(2).setResizable(false);
        tableMP.getColumnModel().getColumn(2).setPreferredWidth(110);
        tableMP.getColumnModel().getColumn(3).setResizable(false);
        tableMP.getColumnModel().getColumn(3).setPreferredWidth(40);
        tableMP.getColumnModel().getColumn(4).setResizable(false);
        tableMP.getColumnModel().getColumn(4).setPreferredWidth(40);
        tableMP.getColumnModel().getColumn(5).setResizable(false);
        tableMP.getColumnModel().getColumn(5).setPreferredWidth(40);

        jLabel5.setText("Memória Principal");

        jLabel6.setText("Memória Secundária");

        jLabel7.setText("células");

        jLabel8.setText("células");

        jLabel9.setText("células");

        textExplicacaoLinha.setText("label Linha");

        jLabel10.setText("Número de faltas de página: ");

        textNumFaltaPaginas.setText("label");

        jlabelTP.setText("Tabela de Páginas");

        jLabel12.setText("Política escolhida:");

        textPolitica.setText("jLabel13");

        textRelogio.setText("label");

        jLabel13.setText("Relógio");

        tableMS.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Quadro", "# do Processo", "# da Página", "V"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableMS.setCellSelectionEnabled(true);
        jScrollPane2.setViewportView(tableMS);
        tableMS.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableMS.getColumnModel().getColumn(0).setResizable(false);
        tableMS.getColumnModel().getColumn(0).setPreferredWidth(60);
        tableMS.getColumnModel().getColumn(1).setResizable(false);
        tableMS.getColumnModel().getColumn(1).setPreferredWidth(110);
        tableMS.getColumnModel().getColumn(2).setResizable(false);
        tableMS.getColumnModel().getColumn(2).setPreferredWidth(110);
        tableMS.getColumnModel().getColumn(3).setResizable(false);
        tableMS.getColumnModel().getColumn(3).setPreferredWidth(40);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(98, 98, 98)
                                            .addComponent(jLabel5))
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(162, 162, 162)
                                            .addComponent(jLabel6))
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(74, 74, 74)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createSequentialGroup()
                                                    .addComponent(jLabel4)
                                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                    .addComponent(textTamMemSec)
                                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                    .addComponent(jLabel9))
                                                .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)))))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jLabel13)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(textRelogio)
                                            .addGap(18, 18, 18)
                                            .addComponent(jLabel10)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(textNumFaltaPaginas))
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(textExplicacaoLinha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                .addComponent(jLabel2)
                                                .addGap(58, 58, 58)
                                                .addComponent(textLinha, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(btnLerProxLinha))))
                                    .addGap(270, 270, 270)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(textTamMemPrinc)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel8)))
                        .addGap(55, 55, 55)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tabelasDePaginaPane, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jlabelTP))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(textTamPagina)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel7))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textPolitica)))
                .addGap(103, 103, 103))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textTamMemPrinc)
                    .addComponent(jLabel8)
                    .addComponent(jLabel4)
                    .addComponent(textTamMemSec)
                    .addComponent(jLabel9)
                    .addComponent(jLabel1)
                    .addComponent(textTamPagina)
                    .addComponent(jLabel7))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(textPolitica))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jlabelTP)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(tabelasDePaginaPane, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(115, 115, 115)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(textRelogio)
                    .addComponent(jLabel10)
                    .addComponent(textNumFaltaPaginas))
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLerProxLinha)
                    .addComponent(textLinha)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(textExplicacaoLinha)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLerProxLinhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLerProxLinhaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnLerProxLinhaActionPerformed

    private void btnLerProxLinhaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLerProxLinhaMouseClicked
        try {
            //Leitura e interpretação da próxima linha do arquivo de entrada.
            String[] linhaAtual = new String[3];
            String linha = in.readLine();
            this.textLinha.setText(linha);
            if (linha == null || linha.equals("")) {
                JOptionPane.showMessageDialog(this, "Fim do arquivo.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
                in.close();
                this.btnLerProxLinha.setVisible(false);
                return;
            }
            this.textRelogio.setText(String.valueOf(++relogio));
            linhaAtual = linha.split(" ");
            int idProcesso = Integer.parseInt(linhaAtual[0]);
            char operacao = linhaAtual[1].charAt(0);
            int param3 = Integer.parseInt(linhaAtual[2], 2);

            //Execução da operação indicada pela linha lida do arquivo texto.
            switch (operacao) {
                case OPERACAO_NEW: {
                    this.textExplicacaoLinha.setText("Submissão do Processo " + idProcesso + ", de tamanho " + param3);
                    int numeroDePaginas = param3 / Pagina.getTAMANHO();
                    String numPaginasBin = Integer.toBinaryString(numeroDePaginas);
                    int bitsNumPaginas = numPaginasBin.length();
                    String maximoOffset = Integer.toBinaryString(Pagina.getTAMANHO());
                    int bitsOffset = maximoOffset.length();
                    int bitsTotal = bitsOffset + bitsNumPaginas;
                    int sobraNumPagina = TelaPrincipal.tamEnderecoLogico - bitsOffset;
                    int maxPaginas = (int) (Math.pow(2, sobraNumPagina));
                    if (maxPaginas < numeroDePaginas) {
                        JOptionPane.showMessageDialog(null, "Processo de tamanho " + param3 + " não pode ser representado com " + TelaPrincipal.tamEnderecoLogico
                                + " bits para página de tamanho " + Pagina.getTAMANHO() + ".\n O processo teria " + numeroDePaginas + " páginas. \n São necessários "
                                + bitsOffset + " para representar o offset. Sobram então " + sobraNumPagina + " bits para representar o numero da página."
                                + "\n O que implica que o número máximo de páginas que podem ser representadas é " + maxPaginas
                                + "\n Para executar esse processo digite um número de bits maior ou igual a " + bitsTotal + " para tamanho do Endereço Lógico com tamanho de página igual a "
                                + Pagina.getTAMANHO() + ".", "Erro", JOptionPane.ERROR_MESSAGE);
                        processosInvalidos.add(idProcesso);
                        processos.add(new Processo(idProcesso, param3));
                    } else {
                        MemoriaSecundaria.adicionarProcesso(idProcesso, param3);
                    }
                    break;
                }
                case OPERACAO_READ: {
                    if (processosInvalidos.indexOf(idProcesso) == -1) {
                        this.textExplicacaoLinha.setText("Leitura da célula " + param3 + ", do Processo " + idProcesso);
                        MemoriaPrincipal.lerInstrucao(idProcesso, param3);
                    }
                    break;
                }
                case OPERACAO_WRITE: {
                    if (processosInvalidos.indexOf(idProcesso) == -1) {
                        this.textExplicacaoLinha.setText("Escrita na célula " + param3 + ", do Processo " + idProcesso);
                        MemoriaPrincipal.escreverInstrucao(idProcesso, param3);
                    }
                    break;
                }
            }
            this.textNumFaltaPaginas.setText(String.valueOf(numFaltaDePaginas));
        } catch (IOException ex) {
            Logger.getLogger(TelaSimulador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnLerProxLinhaMouseClicked

    public static void inicializaJTable(JTable jTable) {

        jTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{},
                new String[]{
                    "# da Página", "# Quadro", "P", "M"
                }) {

            Class[] types = new Class[]{
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean[]{
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });

        jTable.setCellSelectionEnabled(true);
        jTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable.getColumnModel().getColumn(0).setResizable(false);
        jTable.getColumnModel().getColumn(0).setPreferredWidth(110);
        jTable.getColumnModel().getColumn(1).setResizable(false);
        jTable.getColumnModel().getColumn(1).setPreferredWidth(110);
        jTable.getColumnModel().getColumn(2).setResizable(false);
        jTable.getColumnModel().getColumn(2).setPreferredWidth(40);
        jTable.getColumnModel().getColumn(3).setResizable(false);
        jTable.getColumnModel().getColumn(3).setPreferredWidth(40);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaSimulador().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLerProxLinha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel jlabelTP;
    private javax.swing.JTabbedPane tabelasDePaginaPane;
    private javax.swing.JTable tableMP;
    private javax.swing.JTable tableMS;
    private javax.swing.JLabel textExplicacaoLinha;
    private javax.swing.JLabel textLinha;
    private javax.swing.JLabel textNumFaltaPaginas;
    private javax.swing.JLabel textPolitica;
    private javax.swing.JLabel textRelogio;
    private javax.swing.JLabel textTamMemPrinc;
    private javax.swing.JLabel textTamMemSec;
    private javax.swing.JLabel textTamPagina;
    // End of variables declaration//GEN-END:variables
}
